package admin

import (
	"baokaobang/conf"
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"strings"
)

type AddEnrollmentPlan struct {
	Id           int64  `json:"id"`
	CollegeId    int64  `json:"collegeId"`
	Year         int    `json:"year"`
	Batch        int    `json:"batch"`
	MType        int    `json:"mType"`
	UniversityNo int    `json:"universityNo"`
	MajorName    string `json:"majorName"`
	MajorId      string `json:"majorId"`
	StudentNum   int    `json:"studentNum"`
	Tuition      string `json:"tuition"`
}

type AddEnrollmentPlanExcel struct {
	ExcelUrl string `json:"excelUrl"`
}
type EnrollmentPlanListParam struct {
	UniversityId int64  `json:"universityId"`
	Year         int    `json:"year"`
	Batch        int    `json:"batch"`
	MType        int    `json:"mType"`
	MajorName    string `json:"majorName"`
	MajorId      string `json:"majorId"`
	PerPage      int    `json:"perPage"`
	CurPage      int    `json:"curPage"`
}

var (
	EnrollmentBatchMap map[int]string
	EnrollmentMtypeMap map[int]string
)

func init() {
	EnrollmentBatchMap = map[int]string{
		0: "未知",
		1: "本科一批",
		2: "本科二批",
		3: "高职高专",
	}

	EnrollmentMtypeMap = map[int]string{
		0: "未知",
		1: "文科",
		2: "理科",
	}
}

type EnrollmentPlanController struct {
	Ctx iris.Context
}

func (c *EnrollmentPlanController) OptionsExcel() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}

func (c *EnrollmentPlanController) PostExcel() interface{} {
	addExcel := AddEnrollmentPlanExcel{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}

	err = json.Unmarshal(content, &addExcel)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错:%s", err.Error()), "")
	}
	if len(addExcel.ExcelUrl) <= 0 {
		return utils.CommonRes(1000, "请上传excel文件", "")
	}
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}
	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库事务开启失败：%s", err.Error()), "")
	}
	filePath := fmt.Sprintf("%s%s", conf.UploadPrefix.Backend, addExcel.ExcelUrl)
	f, err := excelize.OpenFile(filePath)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("上传的文件无法打开:%s", err.Error()), "")
	}
	sheetList := f.GetSheetMap()
	for _, sheet := range sheetList {
		sheet := strings.TrimSpace(sheet)
		university := new(models.University)
		ok, err := sess.Where("name=?", sheet).Get(university)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("查询%s出错:%s", sheet, err.Error()), "")
		}
		if !ok {
			return utils.CommonRes(1000, fmt.Sprintf("系统中没有找到%s", sheet), "")
		}

		rows := f.GetRows(sheet)
		for i, row := range rows {
			if i == 0 {
				continue
			}
			year := utils.Atoi(row[0])
			if year <= 0 {
				return utils.CommonRes(1000, "请填写年份", "")
			}
			batch := 0
			batchStr := strings.TrimSpace(row[1])
			for batK, batV := range EnrollmentBatchMap {
				if batV == batchStr {
					batch = batK
				}
			}
			if batch <= 0 {
				return utils.CommonRes(1000, "请填写大学批次", "")
			}
			mType := 0
			mTypeStr := strings.TrimSpace(row[2])
			for mtyK, mtyV := range EnrollmentMtypeMap {
				if mtyV == mTypeStr {
					mType = mtyK
				}
			}
			if mType <= 0 {
				return utils.CommonRes(1000, "请填写科目", "")
			}
			universityNo := utils.Atoi(row[3])
			if universityNo <= 0 {
				return utils.CommonRes(1000, "请填写招生代码", "")
			}

			majorName := strings.TrimSpace(row[4])
			if len(majorName) <= 0 {
				return utils.CommonRes(1000, "请填写专业名称", "")
			}
			//majorId := utils.Atoi(row[5])
			majorId := fmt.Sprintf("%02d", row[5])
			if len(majorId) <= 0 {
				return utils.CommonRes(1000, "请填写专业代码", "")
			}
			studentNum := utils.Atoi(row[6])
			if studentNum <= 0 {
				return utils.CommonRes(1000, "请填写招生人数", "")
			}
			tuition := row[7]
			if len(tuition) <= 0 {
				return utils.CommonRes(1000, "请填写学费", "")
			}

			enrollmentPlan := new(models.EnrollmentPlan)
			enrollmentPlan.Year = year
			enrollmentPlan.Batch = batch
			enrollmentPlan.MType = mType
			enrollmentPlan.MajorName = majorName
			enrollmentPlan.MajorCode = majorId
			enrollmentPlan.StudentNum = studentNum
			enrollmentPlan.Tuition = utils.Atoi(tuition)

			_, err = sess.InsertOne(enrollmentPlan)
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("数据导入失败：%s", err.Error()), "")
			}
		}
	}

	err = sess.Commit()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据导入失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "数据导入成功", "")
}

func (c *EnrollmentPlanController) OptionsEdit() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}

func (c *EnrollmentPlanController) PostEdit() interface{} {
	addEnrollmentPlan := AddEnrollmentPlan{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &addEnrollmentPlan)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}
	if addEnrollmentPlan.Id <= 0 {
		return utils.CommonRes(1000, "缺少必要参数", "")
	}
	if addEnrollmentPlan.CollegeId <= 0 {
		return utils.CommonRes(1000, "请选择院校", "")
	}
	if addEnrollmentPlan.Year <= 0 {
		return utils.CommonRes(1000, "请选择年份", "")
	}
	if addEnrollmentPlan.Batch <= 0 {
		return utils.CommonRes(1000, "请选择大学批次", "")
	}
	if addEnrollmentPlan.MType <= 0 {
		return utils.CommonRes(1000, "请选择文理科", "")
	}
	if addEnrollmentPlan.UniversityNo <= 0 {
		return utils.CommonRes(1000, "请填写招生代码", "")
	}
	if len(addEnrollmentPlan.MajorName) <= 0 {
		return utils.CommonRes(1000, "请填写专业名字", "")
	}
	if len(addEnrollmentPlan.MajorId) <= 0 {
		return utils.CommonRes(1000, "请填写专业代码", "")
	}
	if addEnrollmentPlan.StudentNum <= 0 {
		return utils.CommonRes(1000, "请填写招生人数", "")
	}
	if len(addEnrollmentPlan.Tuition) <= 0 {
		return utils.CommonRes(1000, "请填写每年学费", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	enrollmentPlan := new(models.EnrollmentPlan)
	enrollmentPlan.Id = addEnrollmentPlan.Id
	enrollmentPlan.CollegeId = addEnrollmentPlan.CollegeId
	enrollmentPlan.Year = addEnrollmentPlan.Year
	enrollmentPlan.Batch = addEnrollmentPlan.Batch
	enrollmentPlan.MType = addEnrollmentPlan.MType
	enrollmentPlan.MajorName = strings.TrimSpace(addEnrollmentPlan.MajorName)
	enrollmentPlan.MajorCode = addEnrollmentPlan.MajorId
	enrollmentPlan.StudentNum = addEnrollmentPlan.StudentNum
	enrollmentPlan.Tuition = utils.Atoi(addEnrollmentPlan.Tuition)

	_, err = db.Table(new(models.EnrollmentPlan)).ID(addEnrollmentPlan.Id).Update(enrollmentPlan)
	if err != nil {
		return utils.CommonRes(1000, "操作失败", "")
	}
	return utils.CommonRes(20000, "操作成功", "")
}

func (c *EnrollmentPlanController) OptionsDetail() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}

func (c *EnrollmentPlanController) PostDetail() interface{} {
	editParam := utils.EditParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &editParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}
	if len(editParam.Id) <= 0 {
		return utils.CommonRes(1000, "缺少必要参数", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	enrollmentPlan := new(models.EnrollmentPlan)
	ok, err := db.ID(editParam.Id).Get(enrollmentPlan)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("信息获取失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "信息获取失败", "")
	}
	return utils.CommonRes(20000, "信息获取成功", enrollmentPlan)
}

func (c *EnrollmentPlanController) OptionsList() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}

func (c *EnrollmentPlanController) PostList() interface{} {
	enrollmentPlanListParam := EnrollmentPlanListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &enrollmentPlanListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}
	start := (enrollmentPlanListParam.CurPage - 1) * enrollmentPlanListParam.PerPage
	enrollmentPlanListObj := make([]models.EnrollmentPlanObj, 0)

	sess := db.Table("enrollment_plan").Alias("ep").
		Join("INNER", []string{"university", "u"}, "ep.university_id = u.id").
		Limit(enrollmentPlanListParam.PerPage, start)

	if enrollmentPlanListParam.UniversityId > 0 {
		sess = sess.Where("university_id=?", enrollmentPlanListParam.UniversityId)
	}
	if enrollmentPlanListParam.Year > 0 {
		sess = sess.Where("year=?", enrollmentPlanListParam.Year)
	}
	if enrollmentPlanListParam.Batch > 0 {
		sess = sess.Where("batch=?", enrollmentPlanListParam.Batch)
	}
	if enrollmentPlanListParam.MType > 0 {
		sess = sess.Where("m_type=?", enrollmentPlanListParam.MType)
	}
	if len(enrollmentPlanListParam.MajorName) > 0 {
		sess = sess.Where("major_name like ?", fmt.Sprintf("%%%s%%", enrollmentPlanListParam.MajorName))
	}
	if len(enrollmentPlanListParam.MajorId) > 0 {
		sess = sess.Where("major_id=?", enrollmentPlanListParam.MajorId)
	}

	err = sess.Find(&enrollmentPlanListObj)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获大学招生录取数据列表:%s", err.Error()), "")
	}

	//countSess := db.Where("id>?", 0)
	countSess := db.NewSession()
	if enrollmentPlanListParam.UniversityId > 0 {
		countSess = countSess.Where("university_id=?", enrollmentPlanListParam.UniversityId)
	}

	if enrollmentPlanListParam.Year > 0 {
		countSess = countSess.Where("year=?", enrollmentPlanListParam.Year)
	}
	if enrollmentPlanListParam.Batch > 0 {
		countSess = countSess.Where("batch=?", enrollmentPlanListParam.Batch)
	}
	if enrollmentPlanListParam.MType > 0 {
		countSess = countSess.Where("m_type=?", enrollmentPlanListParam.MType)
	}
	if len(enrollmentPlanListParam.MajorName) > 0 {
		countSess = countSess.Where("major_name like ?", fmt.Sprintf("%%%s%%", enrollmentPlanListParam.MajorName))
	}
	if len(enrollmentPlanListParam.MajorId) > 0 {
		countSess = countSess.Where("major_id=?", enrollmentPlanListParam.MajorId)
	}

	total, err := countSess.Count(new(models.EnrollmentPlan))
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取招生录取数据列表:%s", err.Error()), "")
	}

	for i, epObj := range enrollmentPlanListObj {
		enrollmentPlanListObj[i].BatchShow = EnrollmentBatchMap[epObj.Batch]
		enrollmentPlanListObj[i].EnrollmentPlan.TypeShow = EnrollmentMtypeMap[epObj.EnrollmentPlan.MType]
	}

	data := map[string]interface{}{
		"total": total,
		"list":  enrollmentPlanListObj,
	}

	return utils.CommonRes(20000, "成功获取招生录取数据列表", data)
}

func (c *EnrollmentPlanController) OptionsDel() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}

func (c *EnrollmentPlanController) PostDel() interface{} {
	delParam := utils.DelParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &delParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错：%s", err.Error()), "")
	}

	if len(delParam.Ids) <= 0 {
		return utils.CommonRes(1000, "请提供要删除项的", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}
	ids := strings.Split(delParam.Ids, ",")
	for _, id := range ids {
		enrollmentPlan := new(models.EnrollmentPlan)
		db.ID(id).Get(enrollmentPlan)
		db.Id(id).Delete(enrollmentPlan)
	}

	return utils.CommonRes(20000, "操作成功", "")
}
